package com.zoe.onelink.core.encryptor.algorithm;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.common.exception.ApiException;
import com.zoe.onelink.core.property.EncryptKeyPair;
import com.zoe.onelink.core.property.OnelinkProperties;
import com.zoe.onelink.util.StrUtil;

import java.util.Base64;

/**
 * <p>标题: 国密SM4,对称加密</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-11-12
 */
public class Sm4EncryptFieldAlgorithm extends AbstractEncryptFieldAlgorithm {

    private final SM4 sm4;

    public Sm4EncryptFieldAlgorithm(OnelinkProperties onelinkProperties, EncryptKeyPair keyPair) {

        super(onelinkProperties.getWeb().getEncrypt());

        if (keyPair == null || StrUtil.isBlank(keyPair.getPrivateKey())) {
            this.ex = ApiException.createEx(ExceptionCodeEnum.SERIALIZATION_ENCRYPT_KEY_PAIR_NOT_NULL, "SM4", "PRIVATE KEY");
            this.sm4 = null;
        } else {
            this.sm4 = SmUtil.sm4(Base64.getDecoder().decode(keyPair.getPrivateKey()));
        }

    }

    @Override
    protected String doEncrypt(String text) {
        if (this.ex != null) {
            throw ex;
        }
        return this.sm4.encryptBase64(text);
    }

    @Override
    protected String doDecrypt(String text) {
        if (this.ex != null) {
            throw ex;
        }
        return this.sm4.decryptStr(text);
    }

}
